<?php
/**
 * Created by PhpStorm.
 * User: 86188
 * Date: 2021/3/5
 * Time: 14:57
 */

namespace app\index\controller;


use app\service\apiService;
use app\service\billService;
use app\service\wxtplService;
use think\Controller;
use app\index\controller\Basewx;
use think\Db;
use think\Log;

class Billcheck extends Basewx
{
    public function index(){
        $id=request()->get("id");

        $info=Db::table("bill_check")->where("id",$id)->find();
        if(empty($info)){
            return "<div style='text-align: center;font-size:60px;margin-top:50px'>该订单不存在</div>";
        }
        if($info["check_status"]!="2"){
            return "<div style='text-align: center;font-size:60px;margin-top:50px'>该订单已审核完成</div>";
        }
        $this->assign("info",$info);

        $billinfo=Db::table("bill")->where("id",$info["billid"])->find();
        if(empty($billinfo)){
            return "<div style='text-align: center;font-size:60px;margin-top:50px'>该订单不存在</div>";
        }
        if($billinfo["status"]!="WAIT_PAYMENT"){
            return "<div style='text-align: center;font-size:60px;margin-top:50px'>该订单已支付，无法审核</div>";
        }
        $this->assign("billinfo",$billinfo);
        return View::fetch();
    }

    //保存
    public function checksuccess(){
        $id=request()->get("id");
        $info=Db::table("bill_check")->where("id",$id)->find();
        if(empty($info)){
            return "<div style='text-align: center;font-size:60px;margin-top:50px'>该订单不存在</div>";
        }
        if($info["check_status"]!="2"){
            return "<div style='text-align: center;font-size:60px;margin-top:50px'>该订单已审核完成</div>";
        }
        $this->assign("info",$info);

        $billinfo=Db::table("bill")->where("id",$info["billid"])->find();
        if(empty($billinfo)){
            return "<div style='text-align: center;font-size:60px;margin-top:50px'>该订单不存在</div>";
        }
        if($billinfo["status"]!="WAIT_PAYMENT"){
            return "<div style='text-align: center;font-size:60px;margin-top:50px'>该订单已支付，无法审核</div>";
        }

        if($billinfo["tongbu"]=="2"){
            Db::startTrans();
            try{
                //更新账单状态
                Db::table('bill')
                    ->where("id",$info["billid"])
                    ->update([
                            "bill_entry_amount"=>$info["bill_entry_amount"],
                            "acct_period"=>$info["acct_period"]
                        ]
                    );

                Db::table("bill_check")
                    ->where("id",$id)
                    ->update([
                        "check_status"=>1,
                        "check_time"=>time(),
                        "check_openid"=>session("user_id")
                    ]);
                // 提交事务
                Db::commit();

                //给用户发送账单更新成功通知
                $admininfo=Db::table("admin")->where("name",$info["username"])->find();
                if((!empty($admininfo))&&($admininfo["openid"]!='0')){
                    $openid=$admininfo["openid"];
                    $url="";
                    $first="您的账单修改成功";
                    $keyword1="账单修改";

                    $keyword2="修改成功";
                    $keyword3="同意";
                    $remark="";
                    $data=(new wxtplService())->json_tempalte_checksuccess($openid,$url,$first,$keyword1,$keyword2,$keyword3,$remark);
                    $access_token=(new Basewxget())->gettoken();
                    $url="https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=".$access_token;
                    $res=(new wxtplService())->curl_post($url,$data);
                    Log::write($res,"wxusermsg");
                }
                return "<div style='text-align: center;font-size:60px;margin-top:50px'>账单审核成功</div>";
            } catch (\Exception $e) {
                // 回滚事务

                Db::rollback();
                return "<div style='text-align: center;font-size:60px;margin-top:50px'>".$e->getMessage()."</div>";
            }

        }elseif($billinfo["tongbu"]=="1"){
            //已上线支付宝

            $token = (new billService())->billinfoToken($info['community_id']);

            $api = new apiService(config('app')['roombilledit'], 'https://openapi.alipay.com/gateway.do');
            $res = $api->roomBillEdit(json_encode(['batch_id' => $billinfo['batch_id'], 'community_id' =>  $billinfo['community_id'], 'bill_entry_id' => $billinfo['bill_entry_id'],'out_room_id' => $billinfo['out_room_id'], 'room_address' => $billinfo['room_address'], 'cost_type' => $billinfo['cost_type'], 'bill_entry_amount' => $info['bill_entry_amount'], 'acct_period' => $info['acct_period'], 'release_day' => $billinfo['release_day'], 'deadline' => $billinfo['deadline'],  'token' => $token]));

            //判断是否存入支付宝
            if (!isset($res['error'])){
                $resu=$res['success'];
                if(isset($resu->alive_bill_entry_list)){
                    return "<div style='text-align: center;font-size:60px;margin-top:50px'>账单支付中无法修改</div>";
                }
                Db::table('bill')
                    ->where("id",$info["billid"])
                    ->update([
                            "bill_entry_amount"=>$info["bill_entry_amount"],
                            "acct_period"=>$info["acct_period"]
                        ]
                    );

                Db::table("bill_check")
                    ->where("id",$id)
                    ->update([
                        "check_status"=>1,
                        "check_time"=>time(),
                        "check_openid"=>session("user_id")
                    ]);

                //给用户发送账单更新成功通知
                $admininfo=Db::table("admin")->where("name",$info["username"])->find();
                if((!empty($admininfo))&&($admininfo["openid"]!='0')){
                    $openid=$admininfo["openid"];
                    $url="";
                    $first="您的账单修改成功";
                    $keyword1="账单修改";

                    $keyword2="修改成功";
                    $keyword3="同意";
                    $remark="";
                    $data=(new wxtplService())->json_tempalte_checksuccess($openid,$url,$first,$keyword1,$keyword2,$keyword3,$remark);
                    $access_token=(new Basewxget())->gettoken();
                    $url="https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=".$access_token;
                    $res=(new wxtplService())->curl_post($url,$data);
                    //Log::write($res,"wxusermsg");
                }
                return "<div style='text-align: center;font-size:60px;margin-top:50px'>账单审核成功</div>";

            }else{
                return "<div style='text-align: center;font-size:60px;margin-top:50px'>".$res['error']."</div>";

            }
        }
    }
    public function checkfail(){
        $id=request()->get("id");
        $info=Db::table("bill_check")->where("id",$id)->find();
        if(empty($info)){
            return "<div style='text-align: center;font-size:60px;margin-top:50px'>该订单不存在</div>";
        }
        if($info["check_status"]!="2"){
            return "<div style='text-align: center;font-size:60px;margin-top:50px'>该订单已审核完成</div>";
        }
        $res=Db::table("bill_check")
                ->where("id",$id)
                ->update([
                    "check_status"=>3,
                    "check_time"=>time(),
                    "check_openid"=>session("user_id")
                ]);
        if($res){
            $admininfo=Db::table("admin")->where("name",$info["username"])->find();
            if((!empty($admininfo))&&($admininfo["openid"]!='0')){
                $openid=$admininfo["openid"];
                $url="";
                $first="您的账单修改信息被驳回";
                $keyword1="审核驳回";
                $roominfo=Db::table("roominfo")->where("out_room_id",$info["out_room_id"])->find();
                $communityinfo=Db::table("community")->where("community_id",$info["community_id"])->find();
                $keyword2=$communityinfo["community_name"]."-".$roominfo["address"];
                $remark="";
                $data=(new wxtplService())->json_tempalte_back($openid,$url,$first,$keyword1,$keyword2,$remark);
                $access_token=(new Basewxget())->gettoken();
                $url="https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=".$access_token;
                $res=(new wxtplService())->curl_post($url,$data);
                //Log::write($res,"wxusermsg");

            }
            return "<div style='text-align: center;font-size:60px;margin-top:50px'>该订单已被驳回</div>";
        }else{
            return "<div style='text-align: center;font-size:60px;margin-top:50px'>该订单审核失败</div>";
        }
    }
}